window.addEventListener('DOMContentLoaded',()=>{
    document.querySelector("#addBtn").addEventListener('click',async()=>{
        //获取文本框中的信息
        let sid=document.querySelector("#sid").value
        let sname=document.querySelector("#sname").value
        let age=document.querySelector("#age").value
        //构建个对象
        let student={sid,sname,age}
        const {code,message}=await addStudent(student)
        if(code){
            alert(message)
        }
    })
})

const addStudent=student=>{
    return new Promise((resolve,reject)=>{
        const xhr=new XMLHttpRequest()
        xhr.open("POST","/students/add",true)
        xhr.setRequestHeader("Content-Type","application/json;charset=UTF-8")
        xhr.send(JSON.stringify(student))
        xhr.onreadystatechange=()=>{
            if(xhr.readyState==4){
                if(xhr.status==200){
                   resolve(JSON.parse(xhr.responseText))
                }
            }
        }
    })
}
